package v1

import (
	"bytes"
	"context"
	"encoding/binary"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"time"

	"github.com/lithammer/shortuuid/v4"
	"github.com/pkg/errors"
	"google.golang.org/genproto/googleapis/api/httpbody"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/types/known/emptypb"
	"google.golang.org/protobuf/types/known/timestamppb"

	"quipus/internal/crawl"
	"quipus/internal/database/model"
	"quipus/internal/utils"
	"quipus/pkg/s3"
	v1pb "quipus/proto/gen/api/v1"
	apb "quipus/proto/gen/assist"
	cpb "quipus/proto/gen/common"
)

const (
	// The upload knotry buffer is 32 MiB.
	// It should be kept low, so RAM usage doesn't get out of control.
	// This is unrelated to maximum upload size limit, which is now set through system setting.
	MaxUploadBufferSizeBytes = 32 << 20
	MebiByte                 = 1024 * 1024
)

func (s *APIV1Service) CreateResource(ctx context.Context, request *v1pb.CreateResourceRequest) (*v1pb.Resource, error) {
	user, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
	}

	if request.Type == "LINK" {
		return s.CreateLinkResource(ctx, request)
	}

	create := &model.Resource{
		UID:       shortuuid.New(),
		CreatorID: user.ID,
		Filename:  request.Filename,
		Type:      request.Type,
		TenantID:  user.TenantID,
	}

	systemStorageSetting := s.GetSystemStorageSetting(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get system storage setting: %v", err)
	}
	size := binary.Size(request.Content)
	uploadSizeLimit := int(systemStorageSetting.UploadSizeLimitMb) * MebiByte
	if uploadSizeLimit == 0 {
		uploadSizeLimit = MaxUploadBufferSizeBytes
	}
	if size > uploadSizeLimit {
		return nil, status.Errorf(codes.InvalidArgument, "file size exceeds the limit")
	}
	create.Size = int32(size)
	create.Blob = request.Content
	if err := s.SaveResourceBlob(ctx, create); err != nil {
		return nil, status.Errorf(codes.Internal, "failed to save resource blob: %v", err)
	}

	if request.Knot != nil {
		knotId, err := utils.ExtractIDFromUrn(utils.KnotUrnPrefix, *request.Knot)
		if err != nil {
			return nil, status.Errorf(codes.InvalidArgument, "invalid knot id: %v", err)
		}
		create.KnotID = knotId
	}
	err = s.Gds.Handler.CreateResource(ctx, create)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to create resource: %v", err)
	}

	return s.convertResourceFromDB(ctx, create), nil
}

func (s *APIV1Service) CreateLinkResource(ctx context.Context, request *v1pb.CreateResourceRequest) (*v1pb.Resource, error) {
	user, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
	}

	create := &model.Resource{
		UID:       shortuuid.New(),
		CreatorID: user.ID,
		Filename:  request.Filename,
		Type:      request.Type,
		Reference: request.ExternalLink,
		TenantID:  user.TenantID,
	}

	err = s.Gds.Handler.CreateResource(ctx, create)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to create resource: %v", err)
	}

	return s.convertResourceFromDB(ctx, create), nil
}

func (s *APIV1Service) ListResources(ctx context.Context, _ *v1pb.ListResourcesRequest) (*v1pb.ListResourcesResponse, error) {
	user, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
	}
	resources, _, err := s.Gds.Handler.ListResources(ctx, &apb.FindResource{
		CreatorId: user.ID,
	})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to list resources: %v", err)
	}

	response := &v1pb.ListResourcesResponse{}

	userMap := make(map[int32]*v1pb.User)
	// for _, subject := range subjects {
	// 	subjectMsg, err := s.convertSubjectFromDB(ctx, subject, userId)
	// 	if err != nil {
	// 		return nil, errors.Wrap(err, "failed to convert subject")
	// 	}
	// 	user := userMap[subject.CreatorID]
	// 	if user == nil {
	// 		u, _ := s.Gds.Handler.GetUser(ctx, &apb.FindUser{Id: subject.CreatorID})
	// 		if u == nil {
	// 			continue
	// 		}
	// 		user = s.convertUserFromStore(u)

	// 		if err != nil {
	// 			return nil, errors.Wrap(err, "failed to convert user")
	// 		}
	// 	}

	// 	subjectMsg.Creator = user

	// 	userMap[subject.CreatorID] = user

	// 	subjectMessages = append(subjectMessages, subjectMsg)
	// }

	for _, resource := range resources {
		rMsg := s.convertResourceFromDB(ctx, resource)
		user := userMap[resource.CreatorID]
		if user == nil {
			u, _ := s.Gds.Handler.GetUser(ctx, &apb.FindUser{Id: resource.CreatorID})
			if u == nil {
				continue
			}
			user = s.convertUserFromStore(u)

			if err != nil {
				return nil, errors.Wrap(err, "failed to convert user")
			}
		}
		rMsg.Creator = user
		response.Resources = append(response.Resources, rMsg)
	}
	return response, nil
}

func (s *APIV1Service) GetResource(ctx context.Context, request *v1pb.GetResourceRequest) (*v1pb.Resource, error) {
	id, err := utils.ExtractIDFromUrn(utils.ResourceUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid resource id: %v", err)
	}
	resource, err := s.Gds.Handler.GetResource(ctx, &apb.FindResource{
		Id: id,
	})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get resource: %v", err)
	}
	if resource == nil {
		return nil, status.Errorf(codes.NotFound, "resource not found")
	}
	return s.convertResourceFromDB(ctx, resource), nil
}

//nolint:all
func (s *APIV1Service) GetResourceByUid(ctx context.Context, request *v1pb.GetResourceByUidRequest) (*v1pb.Resource, error) {
	resource, err := s.Gds.Handler.GetResource(ctx, &apb.FindResource{
		Uid: request.Uid,
	})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get resource: %v", err)
	}
	if resource == nil {
		return nil, status.Errorf(codes.NotFound, "resource not found")
	}
	return s.convertResourceFromDB(ctx, resource), nil
}

func (s *APIV1Service) GetResourceBinary(ctx context.Context, request *v1pb.GetResourceBinaryRequest) (*httpbody.HttpBody, error) {
	resourceFind := &apb.FindResource{
		FindBlob: true,
	}
	if request.Urn != "" {
		id, err := utils.ExtractIDFromUrn(utils.ResourceUrnPrefix, request.Urn)
		if err != nil {
			return nil, status.Errorf(codes.InvalidArgument, "invalid resource id: %v", err)
		}
		resourceFind.Id = id
	}
	resource, err := s.Gds.Handler.GetResource(ctx, resourceFind)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get resource: %v", err)
	}
	if resource == nil {
		return nil, status.Errorf(codes.NotFound, "resource not found")
	}
	// Check the related knot visibility.
	if resource.KnotID > 0 {
		knot, err := s.Gds.Handler.GetKnot(ctx, &apb.FindKnot{
			Id: resource.KnotID,
		})
		if err != nil {
			return nil, status.Errorf(codes.Internal, "failed to find knot by ID: %v", resource.KnotID)
		}
		if knot != nil && knot.Visibility != cpb.Visibility_PUBLIC.String() {
			user, err := s.GetCurrentUser(ctx)
			if err != nil {
				return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
			}
			if user == nil {
				return nil, status.Errorf(codes.Unauthenticated, "unauthorized access")
			}
			if knot.Visibility == cpb.Visibility_PRIVATE.String() && user.ID != resource.CreatorID {
				return nil, status.Errorf(codes.Unauthenticated, "unauthorized access")
			}
		}
	}

	blob := resource.Blob
	if resource.StorageType == apb.ResourceStorageType_LOCAL.String() {
		resourcePath := filepath.FromSlash(resource.Reference)
		if !filepath.IsAbs(resourcePath) {
			resourcePath = filepath.Join(s.Profile.Data, resourcePath)
		}

		file, err := os.Open(resourcePath)
		if err != nil {
			if os.IsNotExist(err) {
				return nil, status.Errorf(codes.NotFound, "file not found for resource: %s", request.Urn)
			}
			return nil, status.Errorf(codes.Internal, "failed to open the file: %v", err)
		}
		defer file.Close()
		blob, err = io.ReadAll(file)
		if err != nil {
			return nil, status.Errorf(codes.Internal, "failed to read the file: %v", err)
		}
	}

	contentType := resource.Type
	if strings.HasPrefix(contentType, "text/") {
		contentType += "; charset=utf-8"
	}

	httpBody := &httpbody.HttpBody{
		ContentType: contentType,
		Data:        blob,
	}
	return httpBody, nil
}

func (s *APIV1Service) UpdateResource(ctx context.Context, request *v1pb.UpdateResourceRequest) (*v1pb.Resource, error) {
	id, err := utils.ExtractIDFromUrn(utils.ResourceUrnPrefix, request.Resource.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid resource id: %v", err)
	}
	if request.UpdateMask == nil || len(request.UpdateMask.Paths) == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "update mask is required")
	}

	currentTs := time.Now().Unix()
	update := &apb.UpdateResource{
		Id:        id,
		UpdatedTs: timestamppb.New(time.Unix(currentTs, 0)),
	}
	for _, field := range request.UpdateMask.Paths {
		if field == "filename" {
			update.Filename = request.Resource.Filename
		} else if field == "knot" {
			if request.Resource.Knot == nil {
				return nil, status.Errorf(codes.InvalidArgument, "knot is required")
			}
			knotID, err := utils.ExtractIDFromUrn(utils.KnotUrnPrefix, *request.Resource.Knot)
			if err != nil {
				return nil, status.Errorf(codes.InvalidArgument, "invalid knot id: %v", err)
			}
			update.KnotId = knotID
		}
	}

	if err := s.Gds.Handler.UpdateResource(ctx, update); err != nil {
		return nil, status.Errorf(codes.Internal, "failed to update resource: %v", err)
	}
	return s.GetResource(ctx, &v1pb.GetResourceRequest{
		Urn: request.Resource.Urn,
	})
}

func (s *APIV1Service) DeleteResource(ctx context.Context, request *v1pb.DeleteResourceRequest) (*emptypb.Empty, error) {
	id, err := utils.ExtractIDFromUrn(utils.ResourceUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid resource id: %v", err)
	}
	user, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
	}
	resource, err := s.Gds.Handler.GetResource(ctx, &apb.FindResource{
		Id:        id,
		CreatorId: user.ID,
	})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to find resource: %v", err)
	}
	if resource == nil {
		return nil, status.Errorf(codes.NotFound, "resource not found")
	}
	// Delete the resource from the database.
	if err := s.Gds.Handler.DeleteResource(ctx, &apb.DeleteResource{
		Id: resource.ID,
	}); err != nil {
		return nil, status.Errorf(codes.Internal, "failed to delete resource: %v", err)
	}
	return &emptypb.Empty{}, nil
}

// SaveResourceBlob save the blob of resource based on the storage config.
func (s *APIV1Service) SaveResourceBlob(ctx context.Context, create *model.Resource) error {
	systemStorageSetting := s.GetSystemStorageSetting(ctx)

	if systemStorageSetting.StorageType.String() == v1pb.StorageType_LOCAL.String() {
		filepathTemplate := "assets/{timestamp}_{filename}"
		if systemStorageSetting.FilepathTemplate != "" {
			filepathTemplate = systemStorageSetting.FilepathTemplate
		}

		internalPath := filepathTemplate
		if !strings.Contains(internalPath, "{filename}") {
			internalPath = filepath.Join(internalPath, "{filename}")
		}
		internalPath = replaceFilenameWithPathTemplate(internalPath, create.Filename)
		internalPath = filepath.ToSlash(internalPath)

		// Ensure the directory exists.
		osPath := filepath.FromSlash(internalPath)
		if !filepath.IsAbs(osPath) {
			osPath = filepath.Join(s.Profile.Data, osPath)
		}
		dir := filepath.Dir(osPath)
		if err := os.MkdirAll(dir, os.ModePerm); err != nil {
			return errors.Wrap(err, "Failed to create directory")
		}
		dst, err := os.Create(osPath)
		if err != nil {
			return errors.Wrap(err, "Failed to create file")
		}
		defer dst.Close()

		// Write the blob to the file.
		if err := os.WriteFile(osPath, create.Blob, 0644); err != nil {
			return errors.Wrap(err, "Failed to write file")
		}
		create.Reference = internalPath
		create.Blob = nil
		create.StorageType = apb.ResourceStorageType_LOCAL.String()
	} else if systemStorageSetting.StorageType.String() == apb.ResourceStorageType_S3.String() {

		s3Config := systemStorageSetting.S3Config
		if s3Config == nil {
			return errors.Errorf("No actived external storage found")
		}
		s3Client, err := s3.NewClient(ctx, s3Config)
		if err != nil {
			return errors.Wrap(err, "Failed to create s3 client")
		}

		filepathTemplate := systemStorageSetting.FilepathTemplate
		if !strings.Contains(filepathTemplate, "{filename}") {
			filepathTemplate = filepath.Join(filepathTemplate, "{filename}")
		}
		filepathTemplate = replaceFilenameWithPathTemplate(filepathTemplate, create.Filename)
		key, err := s3Client.UploadObject(ctx, filepathTemplate, create.Type, bytes.NewReader(create.Blob))
		if err != nil {
			return errors.Wrap(err, "Failed to upload via s3 client")
		}
		presignURL, err := s3Client.PresignGetObject(ctx, key)
		if err != nil {
			return errors.Wrap(err, "Failed to presign via s3 client")
		}

		pds3 := &apb.ResourcePayload_S3Object_{
			S3Object: &apb.ResourcePayload_S3Object{
				S3Config:          s3Config,
				Key:               key,
				LastPresignedTime: timestamppb.New(time.Now()),
			},
		}

		pb, e := protojson.Marshal(&apb.ResourcePayload{Payload: pds3})
		if e != nil {
			return errors.Wrap(e, "Failed to marshal resource payload")
		}
		create.Reference = presignURL
		create.Blob = nil
		create.StorageType = apb.ResourceStorageType_S3.String()
		create.Payload = string(pb)
	}

	return nil
}

var fileKeyPattern = regexp.MustCompile(`\{[a-z]{1,9}\}`)

func replaceFilenameWithPathTemplate(path, filename string) string {
	t := time.Now()
	path = fileKeyPattern.ReplaceAllStringFunc(path, func(s string) string {
		switch s {
		case "{filename}":
			return filename
		case "{timestamp}":
			return fmt.Sprintf("%d", t.Unix())
		case "{year}":
			return fmt.Sprintf("%d", t.Year())
		case "{month}":
			return fmt.Sprintf("%02d", t.Month())
		case "{day}":
			return fmt.Sprintf("%02d", t.Day())
		case "{hour}":
			return fmt.Sprintf("%02d", t.Hour())
		case "{minute}":
			return fmt.Sprintf("%02d", t.Minute())
		case "{second}":
			return fmt.Sprintf("%02d", t.Second())
		case "{uuid}":
			return utils.GenUUID()
		}
		return s
	})
	return path
}

func (s *APIV1Service) convertResourceFromDB(ctx context.Context, resource *model.Resource) *v1pb.Resource {
	resourceMessage := &v1pb.Resource{
		Urn:        utils.BuildUrn(utils.ResourceUrnPrefix, resource.ID),
		Uid:        resource.UID,
		CreateTime: timestamppb.New(time.Unix(resource.CreatedTs, 0)),
		Filename:   resource.Filename,
		Type:       resource.Type,
		Size:       int64(resource.Size),
	}

	if resource.Type == "LINK" {
		resourceMessage.ExternalLink = resource.Reference
	}

	if resource.StorageType == apb.ResourceStorageType_EXTERNAL.String() || resource.StorageType == apb.ResourceStorageType_S3.String() {
		resourceMessage.ExternalLink = resource.Reference
	}
	if resource.KnotID != 0 {
		knot, _ := s.Gds.Handler.GetKnot(ctx, &apb.FindKnot{
			Id: resource.KnotID,
		})
		if knot != nil {
			knotName := utils.BuildUrn(utils.KnotUrnPrefix, knot.ID)
			resourceMessage.Knot = &knotName
		}
	}

	return resourceMessage
}

func (s *APIV1Service) GetResourcePath(ctx context.Context, id int32) (string, string, error) {
	resourceFind := &apb.FindResource{
		FindBlob: true,
		Id:       id,
	}

	resource, err := s.Gds.Handler.GetResource(ctx, resourceFind)
	if err != nil {
		return "", "", status.Errorf(codes.Internal, "failed to get resource: %v", err)
	}

	if resource == nil {
		return "", "", status.Errorf(codes.NotFound, "resource not found")
	}

	if resource.Type == "LINK" {
		return resource.Reference, resource.Type, nil
	}

	if resource.StorageType == apb.ResourceStorageType_LOCAL.String() {
		resourcePath := filepath.FromSlash(resource.Reference)
		if !filepath.IsAbs(resourcePath) {
			resourcePath = filepath.Join(s.Profile.Data, resourcePath)
		}

		return resourcePath, resource.Type, nil
	}

	return "", "", nil
}

func (s *APIV1Service) GetResourceData(ctx context.Context, urn string) ([]byte, string, error) {
	resourceFind := &apb.FindResource{
		FindBlob: true,
	}
	id, err := utils.ExtractIDFromUrn(utils.ResourceUrnPrefix, urn)
	if err != nil {
		return nil, "", status.Errorf(codes.InvalidArgument, "invalid resource id: %v", err)
	}

	resourceFind.Id = id
	resource, err := s.Gds.Handler.GetResource(ctx, resourceFind)
	if err != nil {
		return nil, "", status.Errorf(codes.Internal, "failed to get resource: %v", err)
	}
	if resource == nil {
		return nil, "", status.Errorf(codes.NotFound, "resource not found")
	}

	if resource.Type == "LINK" {
		c, err := crawl.GetPage(resource.Reference)
		if err != nil {
			return nil, "", status.Errorf(codes.Internal, "failed to crawl the link: %v", err)
		}
		return []byte(c), resource.Type, nil
	}

	blob := []byte{}
	if resource.StorageType == apb.ResourceStorageType_LOCAL.String() {
		resourcePath := filepath.FromSlash(resource.Reference)
		if !filepath.IsAbs(resourcePath) {
			resourcePath = filepath.Join(s.Profile.Data, resourcePath)
		}

		file, err := os.Open(resourcePath)
		if err != nil {
			if os.IsNotExist(err) {
				return nil, "", status.Errorf(codes.NotFound, "file not found for resource: %s", urn)
			}
			return nil, "", status.Errorf(codes.Internal, "failed to open the file: %v", err)
		}
		defer file.Close()
		blob, err = io.ReadAll(file)
		if err != nil {
			return nil, "", status.Errorf(codes.Internal, "failed to read the file: %v", err)
		}
	}

	contentType := resource.Type
	if strings.HasPrefix(contentType, "text/") {
		contentType += "; charset=utf-8"
	}

	return blob, contentType, nil
}
